package jnpf.zcasset.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetDisposeProcessEntity;
import jnpf.zcasset.mapper.ZcAssetDisposeProcessMapper;
import jnpf.zcasset.model.zcassetdisposeprocess.ZcAssetDisposeProcessForm;
import jnpf.zcasset.model.zcassetdisposeprocess.ZcAssetDisposeProcessPagination;
import jnpf.zcasset.service.ZcAssetDisposeProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资产处置过程
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期：
 */
@Service
public class ZcAssetDisposeProcessServiceImpl extends ServiceImpl<ZcAssetDisposeProcessMapper, ZcAssetDisposeProcessEntity> implements ZcAssetDisposeProcessService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;


    @Override
    public List<ZcAssetDisposeProcessEntity> getList(ZcAssetDisposeProcessPagination zcAssetDisposeProcessPagination) {
        return getTypeList(zcAssetDisposeProcessPagination, zcAssetDisposeProcessPagination.getDataType());
    }

    @Override
    public List<ZcAssetDisposeProcessEntity> getTypeList(ZcAssetDisposeProcessPagination zcAssetDisposeProcessPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int zcAssetDisposeProcessNum = 0;
        QueryWrapper<ZcAssetDisposeProcessEntity> zcAssetDisposeProcessQueryWrapper = new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(zcAssetDisposeProcessPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcAssetDisposeProcessPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            int zcAssetDisposeProcessNum1 = 0;
            QueryWrapper<ZcAssetDisposeProcessEntity> zcAssetDisposeProcessSuperWrapper = new QueryWrapper<>();
            zcAssetDisposeProcessNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetDisposeProcessSuperWrapper, superQueryList, matchLogic, "zcAssetDisposeProcess")
                    , new ZcAssetDisposeProcessEntity(), zcAssetDisposeProcessNum1);
            if (zcAssetDisposeProcessNum1 > 0) {
                List<String> zcAssetDisposeProcessList = this.list(zcAssetDisposeProcessSuperWrapper).stream().map(ZcAssetDisposeProcessEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(zcAssetDisposeProcessList);
                intersectionSuperList.add(zcAssetDisposeProcessList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcAssetDisposeProcessObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetDisposeProcessQueryWrapper, zcAssetDisposeProcessPagination.getMenuId(), "zc_asset_dispose_process"));
                if (ObjectUtil.isEmpty(zcAssetDisposeProcessObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetDisposeProcessQueryWrapper = (QueryWrapper<ZcAssetDisposeProcessEntity>) zcAssetDisposeProcessObj;
                    zcAssetDisposeProcessNum++;
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcAssetDisposeProcessObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetDisposeProcessQueryWrapper, zcAssetDisposeProcessPagination.getMenuId(), "zcAssetDisposeProcess"));
                if (ObjectUtil.isEmpty(zcAssetDisposeProcessObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetDisposeProcessQueryWrapper = (QueryWrapper<ZcAssetDisposeProcessEntity>) zcAssetDisposeProcessObj;
                    zcAssetDisposeProcessNum++;
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(zcAssetDisposeProcessPagination.getProcessEvent())) {
                zcAssetDisposeProcessNum++;
                zcAssetDisposeProcessQueryWrapper.lambda().like(ZcAssetDisposeProcessEntity::getProcessEvent, zcAssetDisposeProcessPagination.getProcessEvent());
            }

            if (ObjectUtil.isNotEmpty(zcAssetDisposeProcessPagination.getProcessAgent())) {
                zcAssetDisposeProcessNum++;
                zcAssetDisposeProcessQueryWrapper.lambda().like(ZcAssetDisposeProcessEntity::getProcessAgent, zcAssetDisposeProcessPagination.getProcessAgent());
            }

            if (ObjectUtil.isNotEmpty(zcAssetDisposeProcessPagination.getSketch())) {
                zcAssetDisposeProcessNum++;
                zcAssetDisposeProcessQueryWrapper.lambda().like(ZcAssetDisposeProcessEntity::getSketch, zcAssetDisposeProcessPagination.getSketch());
            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            zcAssetDisposeProcessQueryWrapper.lambda().in(ZcAssetDisposeProcessEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            zcAssetDisposeProcessQueryWrapper.lambda().and(t -> t.in(ZcAssetDisposeProcessEntity::getId, finalAllSuperIDlist));
        }

        //排序
        if (StringUtil.isEmpty(zcAssetDisposeProcessPagination.getSidx())) {
            zcAssetDisposeProcessQueryWrapper.lambda().orderByDesc(ZcAssetDisposeProcessEntity::getId);
        } else {
            try {
                String sidx = zcAssetDisposeProcessPagination.getSidx();
                ZcAssetDisposeProcessEntity zcAssetDisposeProcessEntity = new ZcAssetDisposeProcessEntity();
                Field declaredField = zcAssetDisposeProcessEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zcAssetDisposeProcessQueryWrapper = "asc".equals(zcAssetDisposeProcessPagination.getSort().toLowerCase()) ? zcAssetDisposeProcessQueryWrapper.orderByAsc(value) : zcAssetDisposeProcessQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZcAssetDisposeProcessEntity> page = new Page<>(zcAssetDisposeProcessPagination.getCurrentPage(), zcAssetDisposeProcessPagination.getPageSize());
                IPage<ZcAssetDisposeProcessEntity> userIPage = this.page(page, zcAssetDisposeProcessQueryWrapper);
                return zcAssetDisposeProcessPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZcAssetDisposeProcessEntity> list = new ArrayList();
                return zcAssetDisposeProcessPagination.setData(list, list.size());
            }
        } else {
            return this.list(zcAssetDisposeProcessQueryWrapper);
        }
    }


    @Override
    public ZcAssetDisposeProcessEntity getInfo(String id) {
        QueryWrapper<ZcAssetDisposeProcessEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetDisposeProcessEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcAssetDisposeProcessEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcAssetDisposeProcessEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ZcAssetDisposeProcessEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法


    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcAssetDisposeProcessForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        if (isUp) {
            id = form.getId();
        }
        if (total > 0) {
            return true;
        }
        return false;
    }


}
